#!-*- coding:utf-8 -*-
import os

DIR_NAME = "java"

INPUT_FILE_PATH = "E:\\ebook"

OUTPUT_FILE_NAME = "README.md"


def list_file(dir_name):
    """
    查询出目录下所有的子目录以及子目录里的文件名
    :param dir_name:
    :return:
    """
    global DIR_NAME
    result_list = ["## ebook\n", "> 个人收集一些计算机相关的书籍\n"]
    if not dir_name or not os.path.isdir(dir_name):
        print("this is a error dir")
    else:
        for file_dir_name in os.listdir(dir_name):
            if os.path.isdir(os.path.abspath(file_dir_name)) and file_dir_name != ".git":
                child_dir = os.path.abspath(file_dir_name)
                DIR_NAME = file_dir_name
                result_list.append("\n\n## " + file_dir_name + "\n")
                for file_name in os.listdir(child_dir):
                    # 只处理文件,不处理子目录里面的内容了
                    if not os.path.isdir(os.path.abspath(file_name)):
                        result_list.append(handler_target(file_name))

    write2file(result_list)


def handler_target(target):
    """
    处理文件的每一行
    :param target:
    :return:
    """
    global DIR_NAME
    if target and ('.pdf' in target or '.doc' in target or '.docx' in target):
        last_index = target.rindex('.')
        return '* [' + target[:last_index] + ']' + '(' + DIR_NAME + '/' + target[:] + ')'
    else:
        return target


def write2file(result_list):
    """
    读取文件的每一行进行处理
    :param result_list:
    :return:
    """
    # 处理完之后写文件
    if result_list:
        with open(OUTPUT_FILE_NAME, 'w+') as f:
            for line in result_list:
                if line:
                    f.write(line)
                    f.write('\n')


if __name__ == "__main__":
    list_file(INPUT_FILE_PATH)
